#Kiwi Editor is a framework for building WYSIWYG web editors.
#Copyright (C) 2011  Roosevelt de Lima Sardinha

#This program is free software; you can redistribute it and/or
#modify it under the terms of the GNU General Public License
#as published by the Free Software Foundation; either version 2
#of the License, or (at your option) any later version.

#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.

#You should have received a copy of the GNU General Public License
#along with this program; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

#Contact the author at roosevelt1@gmail.com (Roosevelt) 


# == Schema Information
# Schema version: 20101204202135
#
# Table name: documents
#
#  id          :integer         not null, primary key
#  name        :string(255)
#  description :string(255)
#  created_at  :datetime
#  updated_at  :datetime
#

class Document < ActiveRecord::Base
  attr_accessible :name, :description
  
  validates :name, :presence => true
  validates :description, :presence => true
  
  has_many :eos, :dependent => :destroy
  
  def update_with_json(json)
    as_json = ActiveSupport::JSON
    # Save document to the database 
    self.name = json["name"]
    self.description = json["description"]
   
    # Remove old if eos if they exist
    Eo.find_all_by_document_id(self.id).each do |eo|
      Eo.destroy(eo)
    end
    
    eos = json["eos"]
    
    # Save new eos to the database
    eos.each do | eo_data |
      eo = self.eos.build
      eo.properties = as_json.encode(eo_data["properties"])
      eo.type_name = eo_data["type"]
      eo.save  
    end
     
    self.save
  end
    
  def to_hash
    as_json = ActiveSupport::JSON
    all_eo_data_array = []
    eo_data = {}  
    self.eos.all.each do |eo|
      eo_data = {}
      eo_data["properties"] = as_json.decode(eo.properties)
      eo_data["type-name"] = EoType.find_by_id(eo.eo_type_id).type_name
      all_eo_data_array << eo_data           
    end   
    
    all_document_data = {}
    all_document_data["id"] = self.id
    all_document_data["name"] = self.name
    all_document_data["description"] = self.description
    all_document_data["eos"] = all_eo_data_array 
    
    return all_document_data
  end     
    
end
